package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class Client {
    /*
       java.net.Socket 套接字
       Socket封装了TCP协议的通讯细节，使得我们使用它就可以和服务端建立链接并
       基于两条流的读写操作完成与远端计算机的交互。
       我们可以把Socket想象为"电话"。
    */
    private Socket socket;

    public Client() {
        try {

            System.out.println("正在链接服务端");
            socket = new Socket("172.88.29.66", 8786);
            System.out.println("链接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            //启动一个线程用来读取服务端发送过来的消息
            ServerHandler serverHandler = new ServerHandler();
            Thread t = new Thread(serverHandler);
            t.setDaemon(true);
            t.start();

            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);

            Scanner scan = new Scanner(System.in);
            System.out.println("请输入：");
            while (true) {
                String line = scan.nextLine();
                if ("exit".equalsIgnoreCase(line)) {
                    break;
                }
                pw.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }

    //该线程负责读取服务端发送过来的消息
    private class ServerHandler implements Runnable {
        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, "UTF-8");
                BufferedReader br = new BufferedReader(isr);
//                while ((br.readLine()) != null){
//                    //读取服务器发送过来的一行字符串
//                    System.out.println(br.readLine());
//                }
                String line;
                while((line = br.readLine())!=null){
                    System.out.println(line);
                }
            } catch (IOException e) {

            }
        }
    }
}
